<template>
  <div class="register-container">
    <el-form ref="dataForm" :model="postForm" :rules="registerRules" class="register-form" autocomplete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">用户注册</h3>
      </div>
      <el-form-item prop="realName">
        <span class="svg-container svg-required">
         * <svg-icon icon-class="user" />姓名
        </span>
        <el-input
          ref="realName"
          class="requiredInput"
          v-model="postForm.realName"
          placeholder="姓名"
          name="realName"
          type="text"
          tabindex="1"
          maxlength="10"
          autocomplete="off"
        />
      </el-form-item>

      <el-form-item prop="mobile">
        <span class="svg-container">
         * <i class="el-icon-mobile-phone" />手机号
        </span>
        <el-input
          id="mobile"
          ref="mobile"
          class="requiredInput"
          v-model="postForm.mobile"
          placeholder="手机号"
          name="mobile"
          type="text"
          tabindex="1"
          maxlength="11"
          autocomplete="off"
          @keyup.native="changeButton"
        />
        <!--<el-button v-waves clearable class="filter-item" style="width: 25%" type="primary" @click="getMessage"></el-button>
        <span id="showCount" style="color: white; display: none">{{ countt }}s</span>-->
        <span class="show-pwd-default" id="sendMessage">
          <el-button :disabled="sendStatus === 0" type="primary"  @click="getMessage()"><span id="btnText">获取验证码</span></el-button>
          <span id="showCount" class="show-pwd-default"  style="color: white; display: none;">{{ countt }}s</span>
        </span>
      </el-form-item>

      <el-form-item prop="code">
        <span class="svg-container">
         * <i class="el-icon-message" />验证码
        </span>
        <el-input
          ref="code"
          class="requiredInput"
          v-model="postForm.code"
          placeholder="验证码"
          name="code"
          type="text"
          tabindex="1"
          autocomplete="off"
          maxlength="4"
          @keyup.native="changeCircle"
        />
        <span class="show-pwd-default" v-if="circleFlag">
          <!--<el-button :type="circleType" :icon="circleIcon" circle></el-button>-->
          <i :style="circleType" :class="circleIcon"></i>
        </span>
      </el-form-item>

      <el-form-item prop="username">
        <span class="svg-container">
         * <svg-icon icon-class="user" />用户名
        </span>
        <el-input
          ref="username"
          class="requiredInput"
          v-model="postForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          maxlength="20"
          autocomplete="off"
          @keyup.native="changeButton"
        />
        <span class="show-pwd-default" id="showPhone">
          <el-button :disabled="phoneAndUserName" type="primary"  @click="getPhone()"><span>同手机号</span></el-button>
        </span>
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="已打开大写" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
           * <svg-icon icon-class="password" />登录密码
          </span>
          <el-input
            id="password"
            :key="passwordType"
            ref="password"
            class="requiredInput"
            v-model="postForm.password"
            :type="passwordType"
            placeholder="登录密码"
            name="password"
            tabindex="2"
            autocomplete="off"
            maxlength="18"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
<!--          <span style="color: red" class="frm_tips">新密码至少包含大写字母，小写字母，数字，且不少于8位</span>-->
        </el-form-item>
      </el-tooltip>

      <el-tooltip v-model="capsTooltip" content="已打开大写" placement="right" manual>
        <el-form-item prop="repassword">
          <span class="svg-container">
           * <svg-icon icon-class="password" />确认密码
          </span>
          <el-input
            :key="passwordType"
            ref="repassword"
            class="requiredInput"
            v-model="postForm.repassword"
            :type="passwordType"
            placeholder="确认密码"
            name="password"
            tabindex="2"
            style="margin-top: 7px"
            autocomplete="off"
            maxlength="18"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-form-item prop="idcard">
        <span class="svg-container">
         * <i class="el-icon-tickets" />身份证号
        </span>
        <el-input
          ref="idcard"
          class="requiredInput"
          v-model="postForm.idcard"
          placeholder="身份证号"
          name="idcard"
          type="text"
          tabindex="1"
          maxlength="18"
          autocomplete="off"
        />
      </el-form-item>

      <el-button :loading="loading" type="primary" :disabled="btnStatus === 0" style="margin-bottom:30px;float: right;" @click.native.prevent="submitForm">注册</el-button>
      <router-link :to="`/`" class="link-type">
        <span>已有账号?点击登录</span>
      </router-link>
    </el-form>
  </div>
</template>

<script>
import { validMobile } from '@/utils/validate'
import { register, checkMoibleCode } from '@/api/register'
import { validateUsername, validateMobile, getValidateCode } from '@/api/system/user'
import { removeAccount } from '@/utils/auth'

export default {
  name: 'Register',
  data() {
    const validateRealname = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        callback(new Error('姓名不能为空'))
      } else {
        this.vaildForBtn.push(rule.field)
        this.vaildEveryRequireInput()
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        callback(new Error('用户名不能为空'))
      } else {
        this.checkUsername(value, callback, rule)
      }
    }
    const validatePassword = (rule, value, callback) => {
      const ruleStr = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#\$%])(?=.*\d)[\s\S]{8,16}$/
      if (!ruleStr.test(value)) {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        callback(new Error('密码需包含数字，大、小写字母，及特殊符号 !@#$% 中的一个或多个,长度 8-18位'))
      } else {
        this.vaildForBtn.push(rule.field)
        this.vaildEveryRequireInput()
        callback()
      }
    }
    const validateRePassword = (rule, value, callback) => {
      const passwd = document.getElementById('password').value
      if (value !== passwd) {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        callback(new Error('两次密码不一致'))
      } else {
        this.vaildForBtn.push(rule.field)
        this.vaildEveryRequireInput()
        callback()
      }
    }
    const validateMobileVal = (rule, value, callback) => {
      if (!validMobile(value)) {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        this.sendStatus = 0
        callback(new Error('手机号格式不正确'))
      } else {
        this.sendStatus = 1
        // this.btnStatus = 1
        // callback()
        this.checkMobile(value, callback, rule)
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        this.vaildForBtn = this.vaildForBtn.filter(item => item !== rule.field) // 去掉验证符号
        this.btnStatus = 0
        callback(new Error('验证码不能为空'))
      } else {
        this.vaildForBtn.push(rule.field)
        this.vaildEveryRequireInput()
        callback()
      }
    }
    return {
      vaildForBtn: [],
      getCodeFlag: false,
      dialogDepartmentVisible: false,
      filterText: '',
      props: {
        label: 'depName',
        value: 'id',
        isLeaf: 'isLeaf'
      },
      selectParams: {
        multiple: false,
        clearable: true,
        placeholder: '请选择部门'
      },
      'check-strictly': true,
      treeParams: {
        clickParent: true,
        filterable: false,
        'check-strictly': true,
        'default-expand-all': false,
        'expand-on-click-node': false,
        data: [],
        props: {
          children: 'children',
          label: 'depName',
          value: 'id'
        }
      },
      postForm: {
        realName: '',
        departmentId: '',
        username: '',
        password: '',
        repassword: '',
        mobile: '',
        // bureauCode: '',
        // freightCode: '',
        // stationCode: '',
        idcard: '',
        code: ''
      },
      registerRules: {
        realName: [{ required: true, trigger: 'change', validator: validateRealname }],
        username: [{ required: true, trigger: 'change', validator: validateUsername }],
        password: [{ required: true, trigger: 'change', validator: validatePassword }
          // {pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/,
          //   message: '密码为数字，小写字母，大写字母，特殊符号 至少包含三种，长度为 8 - 30位'}
        ],
        repassword: [{ required: true, trigger: 'change', validator: validateRePassword }],
        mobile: [{ required: true, trigger: 'change', validator: validateMobileVal }],
        code: [{ required: true, trigger: 'change', validator: validateCode }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      circleType: '',
      circleIcon: '',
      circleFlag: false,
      phoneAndUserName: true,
      departments: [],
      ljAry: [],
      hyzxAry: [],
      czAry: [],
      btnStatus: 0,
      sendStatus: 0,
      countt: 60
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
  },
  created() {
    // 清除cookie的账号，防止密码回显
    removeAccount()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    async loadNode(node, resolve) {
      if (node.level === 0) {
        await listParentsDepartments({ userId: null, authSystemId: this.authSystemId }).then(response => {
          const data = response.data
          this.treeParams.data = data
        })
        return resolve(this.treeParams.data)
      }
      if (node.level >= 1) {
        this.getIndex(node, resolve)
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.depName.indexOf(value) !== -1
    },
    vaildEveryRequireInput() {
      const inputs = document.getElementsByClassName('requiredInput')
      const set = new Set(this.vaildForBtn)
      if (set.size === inputs.length && this.getCodeFlag) {
        this.btnStatus = 1
      }
    },
    getPhone() {
      this.postForm.username = this.postForm.mobile
      this.phoneAndUserName = true
    },
    changeCircle() {
      checkMoibleCode({ mobile: this.postForm.mobile, code: this.postForm.code }).then(response => {
        if (this.Const.OK === response.returnCode) {
          this.circleType = 'color:#67c23A'
          this.circleIcon = 'el-icon-check'
          this.circleFlag = true
        } else {
          this.circleType = 'color:#F56C6C'
          this.circleIcon = 'el-icon-close'
          this.circleFlag = true
        }
      }).catch(() => {
        this.circleType = 'color:#F56C6C'
        this.circleIcon = 'el-icon-close'
        this.circleFlag = true
      })
    },
    changeButton() {
      if (this.postForm.username !== this.postForm.mobile) {
        this.phoneAndUserName = false
      } else {
        this.phoneAndUserName = true
      }
    },
    getMessage() {
      const value = document.getElementById('mobile').value
      if (validMobile(value)) {
        getValidateCode({ mobile: value, type: '1' }).then(response => {
          if (this.Const.OK === response.returnCode) {
            this.$message({
              type: 'success',
              message: '获取验证码成功'
            })
            this.timer = setInterval(this.setTime, 1000)
            this.showCount()
            this.getCodeFlag = true
          } else {
            this.$message({
              type: 'error',
              message: response && response.msg || '验证失败'
            })
            this.showSend()
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '获取验证码失败'
          })
          this.showSend()
        })
      }
    },
    setTime() {
      this.countt--
      if (this.countt < 1) {
        this.countt = 60
        this.showSend()
      } else {
        this.showCount()
      }
    },
    showSend() {
      document.getElementById('btnText').innerHTML = '获取验证码'
      this.sendStatus = 1
      clearInterval(this.timer)
    },
    showCount() {
      document.getElementById('btnText').innerHTML = this.countt + 's'
      this.sendStatus = 0
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    checkUsername(username, callback, rule) {
      validateUsername({ username: username }).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          this.btnStatus = 0
          callback(new Error(response.msg))
        } else {
          this.vaildForBtn.push(rule.field)
          this.vaildEveryRequireInput()
          callback()
        }
      })
    },
    handleCheck() {
      if (this.postForm.username !== this.postForm.mobile) {
        this.postForm.username = this.postForm.mobile
      } else {
        this.postForm.username = ''
      }
    },
    checkMobile(mobile, callback, rule) {
      validateMobile({ mobile: mobile }).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          this.btnStatus = 0
          this.sendStatus = 0
          callback(new Error(response.msg))
        } else {
          this.vaildForBtn.push(rule.field)
          this.vaildEveryRequireInput()
          callback()
        }
      })
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          register(this.postForm).then(response => {
            const returnCode = response && response.returnCode
            if (this.Const.OK === returnCode) {
              this.$message({
                type: 'success',
                message: '注册成功'
              })
              this.$router.back()
            } else {
              this.$message({
                type: 'error',
                message: response && response.msg || '注册失败'
              })
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '注册失败'
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .register-container .el-input input {
    color: $bg;
  }
}

/* reset element-ui css */
.register-container {
  background: url(../../assets/images/register.jpg) no-repeat;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 77%;

    input {
      background: transparent;
      /*border: 0px;*/
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .select-area  .el-input {
    width: 100%;
  }
  .el-form-item {
    /*border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);*/
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$dark_gray:#889aa4;
$light_gray:#eee;

.register-container {
  min-height: 100%;
  width: 100%;
  overflow: hidden;

  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 50px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    color: $light_gray;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 6px;
    color: $light_gray;
    vertical-align: middle;
    text-align: right;
    width: 96px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $light_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  .show-pwd-default {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .show-phone-default{
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>

<style lang="scss">
  .alsj {
    background-color: #3357A1;
  }

  .alsj .is-focusable:hover{
    color: #2b2f3a;
  }
  .alsj .el-tree{
    background-color: #3357A1;
    color: #ffffff;
  }
  .alsj .el-tree-select-popper .el-input__inner {
    background-color: #3357A1;
  }
  .register-department .el-input {
    width: 100%;
  }
  .alsj .el-tree-node__label{
    color: white !important;
  }
  .alsj .el-tree-node__content:hover{
    .el-tree-node__label{
      color: black !important;
    }
    color: black !important;
  }
  #filterText{
    color: black !important;
  }
  .register-form .el-form-item__error{
    margin-left: 96px;
  }
</style>
